package com.eastmoney.emis.edda.infrastructure.encrypt;

import com.eastmoney.emis.edda.config.KeyHolder;
import com.eastmoney.emis.edda.infrastructure.util.OpenPGPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @description: Description
 * @projectName: EDDA-HSBC
 * @package: com.eastmoney.emis.edda.infrastructure.impl
 * @author: 汪程程
 * @date: 2022/9/26 3:47 PM
 * @version: 1.0
 */
@Component
public class HsbcEncryptionImpl implements Encryption {
    @Autowired
    private KeyHolder keyHolder;

    @Override
    public byte[] signAndEncrypt(byte[] data) {
        try {
            return OpenPGPUtils.signAndEncrypt(data,
                    keyHolder.getHsbcPublicKey().getBytes(StandardCharsets.UTF_8),
                    keyHolder.getEmisPrivateKey().getBytes(StandardCharsets.UTF_8),
                    keyHolder.getKeyPassword());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] encrypt(byte[] data) {
        try {
            return OpenPGPUtils.encrypt(data,
                    keyHolder.getHsbcPublicKey().getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] decrypt(byte[] ciphertext) {
        try {
            return OpenPGPUtils.decrypt(ciphertext,
                    keyHolder.getEmisPrivateKey().getBytes(StandardCharsets.UTF_8),
                    keyHolder.getKeyPassword());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] verifyAndDecrypt(byte[] ciphertext) {
        try {
           return OpenPGPUtils.verifyAndDecrypt(ciphertext,
                   keyHolder.getHsbcPublicKey().getBytes(StandardCharsets.UTF_8),
                   keyHolder.getEmisPrivateKey().getBytes(StandardCharsets.UTF_8),
                   keyHolder.getKeyPassword());
       }catch (IOException e) {
           throw new RuntimeException(e);
       }
    }
}
